<template>
  <div ref="chartContainer" class="chartContainer"></div>
</template>

<script>
import * as echarts from "echarts";
export default {
  data() {
    return {
      myChart: null
    };
  },
  methods: {
    initCharts() {
      // 获取图表容器元素
      const chartContainer = this.$refs.chartContainer;
      // 创建ECharts实例
      this.myChart = echarts.init(chartContainer);
      const option = {
        grid: {
          left: "2%", // 网格左侧的距离
          right: "2%", // 网格右侧的距离
          top: "10%", // 网格顶部的距离
          bottom: "10%" // 网格底部的距离
        },
        xAxis: {
          type: "category",
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
        },
        yAxis: {
          type: "value",
          axisLine: {
            show: true
          },
          // 隐藏刻度线
          axisTick: {
            show: true
          }
        },
        series: [
          {
            data: [120, 200, 150, 80, 70, 110, 130],
            type: "bar",
            barMaxWidth: 30,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: "top",
                  formatter: params => {
                    let value = params.value;
                    if (value > 100) {
                      return `${value}/{a|+${100}}`;
                    } else {
                      return `${value}/{b|${-2}}`;
                    }
                  },
                  rich: {
                    a: {
                      color: "red",
                      fontWeight: "bold"
                    },
                    b: {
                      color: "green",
                      fontWeight: "bold"
                    }
                  }
                }
              }
            }
          }
        ]
      };
      // 使用配置项绘制图表
      this.myChart.setOption(option);
    }
  },
  mounted() {
    this.initCharts();
  }
};
</script>

<style lang="scss" scoped>
.chartContainer {
  width: 100%;
  height: 320px;
}
</style>
